package com.lagou.dao;

import com.lagou.domain.User;
import com.lagou.utils.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

public class UserDao {
    public Boolean login(String username, String password) throws SQLException {

        Boolean success = false;

        //1.获取连接
        Connection con = JDBCUtils.getConnection();

        //2.获取Statement对象
        Statement statement = con.createStatement();

        //3.SQL语句
        String sql = "select * from students where username = ? and password = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,username);
        ps.setString(2,password);

        //4.执行查询 获取结果集对象
        ResultSet resultSet = ps.executeQuery();

        //5.处理结果集
        if(resultSet.next()){
            success = true;
            System.out.println("登录成功! 欢迎您: " + username);

        }else{

            System.out.println("登录失败! ");
        }

        //7.关闭流
        JDBCUtils.close(con,statement,resultSet);
        return success;
    }

    public void add(User user) throws SQLException {
        Boolean success = false;

        //1.获取连接
        Connection con = JDBCUtils.getConnection();

        //2.获取Statement对象
        Statement statement = con.createStatement();

        //3.拼接SQL语句
        PreparedStatement ps = con.prepareStatement("INSERT INTO students (username, PASSWORD, gender, birthday) VALUES(?,?,?,?)");

        ps.setObject(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getGender());
        ps.setDate(4,user.getBirthday());
        //4.执行插入
        int result = ps.executeUpdate();

        //5.释放资源
        statement.close();
        ps.close();
        con.close();

    }
}
